<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import type { ComputedRef, Ref } from 'vue'
import { dosendmsgcode, docheckcode } from '../../api/user'
import { showToast } from 'vant';


const router = useRouter()
const telcode = ref('')

const flag: ComputedRef<boolean> = computed(() => {
    return telcode.value.length == 5
})


// 下一步按钮的点击事件
function onSubmit() {

    docheckcode({
        tel: localStorage.getItem('tel'),
        telcode: telcode.value
    }).then(res => {
        // console.log(res);
        if (res.data.code == '200') {
            // 成功
            router.push('/register/step3')
        } else {
            showToast('温馨提示：' + res.data.message)
        }
    })

    // router.push('/register/step3')


}

const text: Ref<string | number> = ref('发送验证码')
const time = ref(10)

const is = ref(false)

// 发送验证码按钮的点击事件
function sendCodeFn() {
    is.value = true
    text.value = time.value

    dosendmsgcode({
        tel: localStorage.getItem('tel')
    }).then(res => {
        console.log(res);
    })

    const timer = setInterval(() => {
        time.value--
        text.value = time.value

        if (time.value == 0) {
            // 关闭定时器
            clearInterval(timer)
            // 恢复默认时间
            time.value = 10
            // 修改按钮内容
            text.value = '再次发送验证码'
            // 继续让按钮可以被点击
            is.value = false
        }
    }, 1000)
}
</script>
<template>
    <div class="content" style="padding: 45px 0;">

        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="telcode" name="" label="验证码" placeholder="请输入验证码"
                    :rules="[{ required: true, message: '请填写验证码' }]">
                    <template #button>
                        <van-button :disabled="is" class="sendcode" @click="sendCodeFn" size="mini">
                            {{ text }}
                        </van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 26px;">
                <van-button :disabled="!flag" round block type="primary" color="#f66" native-type="submit">
                    下一步
                </van-button>
            </div>
        </van-form>
    </div>
</template>
<style lang="scss" scoped>
.sendcode {
    min-width: 60px;
}
</style>